package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.SupplierMapper;
import com.itheima.pojo.Supplier;
import com.itheima.vo.PageResult;
import com.itheima.qo.PageQuery;
import com.itheima.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class SupplierServiceImpl implements SupplierService {

    @Autowired
    private SupplierMapper supplierMapper;


    @Override
    public PageResult pageByMap(PageQuery pageQuery, Map<String, Object> params) {
        // 设置默认值，防止空指针异常
        int page = (pageQuery.getPage() != null) ? pageQuery.getPage() : 1;
        int pageSize = (pageQuery.getPageSize() != null) ? pageQuery.getPageSize() : 10;

        PageHelper.startPage(page, pageSize);
        List<Supplier> supplierList = supplierMapper.listByMap(params);
        Page<Supplier> pagedSuppliers = (Page<Supplier>) supplierList;
        PageResult pageResult = new PageResult();
        pageResult.setCurrentPage(page);
        pageResult.setTotal(pagedSuppliers.getTotal());
        pageResult.setData(pagedSuppliers.getResult());
        pageResult.setPages(pagedSuppliers.getPages());
        return pageResult;
    }

    @Override
    public List<Supplier> listAll() {
        return supplierMapper.listAll();
    }

    @Override
    public Supplier getById(Integer id) {
        return supplierMapper.getById(id);
    }

    @Override
    public void save(Supplier supplier) {
        supplier.setCreateTime(LocalDateTime.now());
        supplier.setUpdateTime(LocalDateTime.now());
        // 如果createBy为空，则设置默认值
        if (supplier.getCreateBy() == null || supplier.getCreateBy().isEmpty()) {
            supplier.setCreateBy("admin"); // 设置默认创建人
        }
        supplier.setIsDel(1);
        supplierMapper.insert(supplier);
    }

    @Override
    public void update(Supplier supplier) {
        supplier.setUpdateTime(LocalDateTime.now());
        supplierMapper.update(supplier);
    }

    @Override
    public void deleteById(Integer id) {
        supplierMapper.deleteById(id);
    }
}